package com.letu.core.utils;


import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
public class ApacheHttpClientsUtils {
    private static CloseableHttpClient httpClient;


    static {

        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        cm.setMaxTotal(200);
        cm.setDefaultMaxPerRoute(20);
        httpClient = HttpClients.custom().setConnectionManager(cm).build();


    }

    //postNoFile
    public static String postForm(String url, Map<String, String> params) {
        HttpPost post = new HttpPost(url);
        if (params == null) {
            return null;
        }
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        for (String key : params.keySet()) {
            list.add(new BasicNameValuePair(key, params.get(key)));
        }
        UrlEncodedFormEntity formEntity;
        try {
            post.setHeader("Content-type", "application/x-www-form-urlencoded");
            post.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            formEntity = new UrlEncodedFormEntity(list, "utf-8");
            post.setEntity(formEntity);
            String paramsJson = JSON.toJSONString(params);
            log.info("开始以POST方式访问路径{}，参数为{}", url, paramsJson);
            CloseableHttpResponse response = httpClient.execute(post);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                String respJson = EntityUtils.toString(entity);
                log.info("访问路径{}成功", url);
                return respJson;
            }
        } catch (UnsupportedEncodingException e) {
            log.error("编码错误", e);
        } catch (ClientProtocolException e) {
            log.error("协议错误", e);
        } catch (IOException e) {
            log.error("IO错误", e);
        } finally {
            post.releaseConnection();
        }
        return null;
    }

}
